package maiyatian.videolive.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import maiyatian.videolive.IActivity;
import maiyatian.videolive.IClickListener;
import maiyatian.videolive.MainActivity;
import maiyatian.videolive.R;
import maiyatian.videolive.adapter.ViewPageAdapter;
import maiyatian.videolive.adapter.main.hotAdapter;
import maiyatian.videolive.bean.DataBean;
import maiyatian.videolive.bean.LiveBean;
import maiyatian.videolive.bean.ParseBean;
import maiyatian.videolive.common.ConstentInfo;
import maiyatian.videolive.live.LiveBoxActivity;
import maiyatian.videolive.live.fragment.StartLiveFragment;
import maiyatian.videolive.main.JsonResponseParser;
import maiyatian.videolive.pulltorefresh.XListView;

/**
 * Created by 王中阳 on 2016/5/9.
 */
public class MainFragment extends LazyFragment implements XListView.IXListViewListener, IClickListener, View.OnClickListener {
    public static final String TAG = "MainFragment";
    // 标志位，标志已经初始化完成。
    private boolean isPrepared;
    /**
     * 是fragment 懒加载已加载过
     */
    private boolean isLoad;
    private String class_id;
    MainActivity mycontext;
    @ViewInject(R.id.xlistview)
    XListView xListView;
    private hotAdapter hotAdapter;
    List<LiveBean> datas;

    public MainFragment() {
    }

    public MainFragment(String class_id) {
        this.class_id = class_id;
    }

    public static MainFragment newInstance() {
        MainFragment fragment = new MainFragment();
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mycontext = (MainActivity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        x.view().inject(this, view);
        isPrepared = true;

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initHeadView();
        xListView.setPullLoadEnable(true);
        xListView.setXListViewListener(this);
        // TODO: 2016/5/12 优化按钮的size 
        com.melnykov.fab.FloatingActionButton fab = (com.melnykov.fab.FloatingActionButton) mycontext.findViewById(R.id.fab);
        fab.attachToListView(xListView);
        fab.setOnClickListener(this);
    }

    private void initHeadView() {
        // TODO: 2016/5/11 滑动vp bottom 点 2广告页和列表的间距

        View view = LayoutInflater.from(mycontext).inflate(R.layout.head_viewpager, null);
        ViewPager viewpager = (ViewPager) view.findViewById(R.id.headviewpager);
        List<ImageView> listtemp = new ArrayList<ImageView>();
        int[] bgs = {R.drawable.ad1, R.drawable.ad2, R.drawable.ad3, R.drawable.ad4};
        for (int i = 0; i < bgs.length; i++) {
            ImageView img = new ImageView(mycontext);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200);
            img.setLayoutParams(layoutParams);
            img.setBackgroundResource(bgs[i]);
            img.setScaleType(ImageView.ScaleType.CENTER_CROP);
            listtemp.add(img);
        }
        ViewPageAdapter viewadapter = new ViewPageAdapter(listtemp);
        xListView.addHeaderView(view);
        LiveBean liveBean = new LiveBean();
        datas = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            liveBean.setLive(true);
//            liveBean.setLiveIntro("直播简介" + i);
//            liveBean.setTopic("话题" + i);
//            datas.add(liveBean);
//        }
        initDatas();
        hotAdapter = new hotAdapter(mycontext, datas, this);
        xListView.setAdapter(hotAdapter);
        viewpager.setAdapter(viewadapter);
    }

    private void initDatas() {
        RequestParams requestParams = new RequestParams(ConstentInfo.MAIN_HOT_URL);
        x.http().get(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                try {
                    String data = result.getString("data");
                    DataBean dataBean = JSON.parseObject(data, DataBean.class);
                    datas = dataBean.getResults();
                    hotAdapter.setDatas(datas);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "onError: " + ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            Log.e(TAG, "lazyLoad=false=" + class_id + ",isPrepared=" + isPrepared + ",isVisible=" + isVisible);
            return;
        }

        if (!isLoad) {
            isLoad = true;
            Log.e(TAG, "isLoad=true=======" + class_id);
            //去请求数据
//            RequestParams params = new RequestParams(HttpUtil.News_Home + "&class_id=" + class_id);
//            httpGet(params, 101);

        }
        Log.e(TAG, "lazyLoad=false=" + class_id + ",isPrepared=" + isPrepared + ",isVisible=" + isVisible);
    }

    @Override
    public void onRefresh() {
        mHandler.sendMessage(mHandler.obtainMessage(102, datas));
    }

    @Override
    public void onLoadMore() {
        mHandler.sendMessage(mHandler.obtainMessage(102, datas));
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 101:
//                    adapter = new ListViewAdapter(activity, cache.generateLocalList());
//                    xlistview.setAdapter(adapter);
//                    //if(adapter != null)
//                    //	adapter.add_updat(cache.generateLocalList());
                    sendEmptyMessage(110);
                    break;
                case 102:
                    //加载数据
//                    cache.update((ArrayList<HolderInfo>) msg.obj);
//                    if (adapter != null) {
//                        adapter.add_updat(cache.generateLocalList());
//                    }
                    initDatas();
                    sendEmptyMessage(101);
                    break;
                case 103:
                    //加载数据
//                    cache.update_nextPullto((ArrayList<HolderInfo>) msg.obj);
//                    if (adapter != null) {
//                        adapter.add_updat(cache.generateLocalList());
//                    }
                    sendEmptyMessage(110);
                    break;
                case 110:
                    xListView.stopRefresh();
                    xListView.stopLoadMore();
                    xListView.setRefreshTime("刚刚");
                    break;
                default:
                    break;
            }

        }

        ;
    };

    @Override
    public void onItemClicked(int position) {
        IActivity.toLiveRoom(getContext());
        mycontext.showToast(mycontext, position + "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab:
                Intent intent = new Intent();
                intent.setClass(getActivity(), LiveBoxActivity.class);
                intent.putExtra(IActivity.PAGETO, StartLiveFragment.TAG);
                startActivity(intent);
                break;
        }
    }
}
